package org.jeecg.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.jeecg.test.TestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
@Component
@ChannelHandler.Sharable
public class MsgHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    TestServiceImpl service;


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel=ctx.channel();
        InetSocketAddress address = (InetSocketAddress)channel.remoteAddress();
        String ip=address.getAddress().getHostAddress();
        int port=address.getPort();
        System.out.println("有client加入-"+ip+":"+port);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel=ctx.channel();
        InetSocketAddress address = (InetSocketAddress)channel.remoteAddress();
        String ip=address.getAddress().getHostAddress();
        int port=address.getPort();
        System.out.println("有client断开连接-"+ip+":"+port);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf in= (ByteBuf) msg;
            byte[] bytes=new byte[in.readableBytes()];//
            service.test(bytes);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);//.addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("触发exceptionCaught");
        cause.printStackTrace();
        ctx.close();
    }
}
